<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="search-container">
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
          查询
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="success" icon="el-icon-edit" @click="handleCreate">
          新增
        </el-button>
      </div>
    </div>

    <el-row :gutter="30">
      <el-col v-for="(item, index) in projects" :key="index" :span="4" :md="8" :sm="12" :xs="24">
        <el-card :body-style="{ padding: '15px' }" shadow="hover" style="margin-bottom: 20px;">
          <section class="card-section" @click.stop="$router.push('/project/detail/' + item.id)">
            <i v-if="checkPermission(['super']) || item.head.id === uuid" class="setting-icon el-icon-setting" @click.stop="handleUpdate(item)" />
            <i v-if="checkPermission(['super']) || item.head.id === uuid" class="delete-icon el-icon-delete" @click.stop="handleDelete(item)" />
            <el-avatar :size="60"> <h2 style="margin:0;padding:0;">{{ item.name }}</h2> </el-avatar>
            <div>
              <h2 style="color: #303133;"> {{ item.name }} </h2>
              <el-badge value="经理" class="item" type="primary">
                <el-button size="small">{{ item.head.nickname }}</el-button>
              </el-badge>
            </div>
          </section>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" :width="'500px'">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 400px; margin-left:40px;">
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="经理" prop="head">
          <el-select v-model="temp.head" class="filter-item" placeholder="请选择" @change="$forceUpdate()">
            <el-option v-for="item in usersOptions" :key="item.id" :label="item.nickname" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="归属部门" prop="organization_id">
          <el-select v-model="temp.organization_id" class="filter-item" placeholder="请选择" @change="$forceUpdate()">
            <el-option v-for="item in organizationsOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="截止日期" prop="deadline_at">
          <el-date-picker v-model="temp.deadline_at" type="datetime" format="yyyy-MM-dd HH:mm" default-time="18:00:00" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择日期" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="temp.intro" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
// import Pagination from '@/components/Pagination'
import checkPermission from '@/utils/permission' // 权限判断函数
import * as UserApi from '@/api/user'
import * as ProjectApi from '@/api/project'
import * as OrganizationApi from '@/api/organization'

export default {
  name: 'Project',
  // components: { Pagination },
  directives: { waves },
  filters: {
    parseTimeFilter(time) {
      if (time) {
        return parseTime(time)
      } else {
        return '∞'
      }
    },
    statusFilter(status) {
      const statusMap = {
        1: 'warning',
        2: 'danger',
        3: 'success',
        4: 'info'
      }
      return statusMap[status]
    },
    statusName(status) {
      const statusMap = {
        1: '未开始',
        2: '进行中',
        3: '已完成',
        4: '取消'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      tableKey: 0,
      pageNo: 1,
      pageSize: 10,
      total: 0,
      projectsLoading: true,
      importanceOptions: [],
      usersOptions: [],
      organizationsOptions: [],
      listQuery: {
        page: 1,
        limit: 10
      },
      projects: [],
      temp: {
        name: '',
        head: '',
        intro: '',
        organization_id: '',
        deadline_at: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        name: [{ required: true, message: '必须填写名称', trigger: 'blur' }],
        // deadline_at: [{ type: 'date', required: false, message: '需要日期类型', trigger: 'blur' }],
        head: [{ required: true, message: '必须填写经理', trigger: 'blur' }]
      }
    }
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ]),
    uuid() {
      return this.$store.state.user.userInfo.id
    }
  },
  created() {
    this.getProjectsList()
    this.getUsers()
    this.getOrganizations()
  },
  methods: {
    checkPermission,
    async getProjectsList(pageQuery) {
      if (pageQuery) {
        this.listQuery = Object.assign(this.listQuery, pageQuery)
      }
      this.projects = []
      this.projectsLoading = true
      const { data } = await ProjectApi.getProjects()
      if (data && data.total) {
        this.projects = data.items
        this.total = data.total
      }
      this.projectsLoading = false
    },
    async getUsers() {
      this.usersOptions = []
      const { data } = await UserApi.getUserList({ pageNo: 1, pageSize: 999 })
      if (data && data.total) {
        this.usersOptions = data.items
      }
    },
    async getOrganizations() {
      this.organizationsOptions = []
      const { data } = await OrganizationApi.getOrganizaitons()
      if (data && data.total) {
        this.organizationsOptions = data.items
      }
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getProjectsList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        name: '',
        intro: '',
        head: '',
        organization_id: '',
        deadline_at: ''
      }
    },
    async handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true

      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(async(valid) => {
        if (valid) {
          await ProjectApi.createProject(this.temp)
          await this.getProjectsList()

          this.dialogFormVisible = false
          await this.$notify({
            title: 'Success',
            message: '新增成功',
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    async handleUpdate(row) {
      this.temp['id'] = row.id
      this.temp['name'] = row.name
      this.temp['head'] = row.head && row.head.id
      this.temp['organization_id'] = row.organization && row.organization.id
      this.temp['intro'] = row.intro
      this.temp['status'] = row.status
      this.temp['deadline_at'] = row.deadline_at
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(async(valid) => {
        if (valid) {
          await ProjectApi.updateProject(this.temp)
          await this.getProjectsList()

          this.dialogFormVisible = false
          this.$notify({
            title: 'Success',
            message: '更新成功',
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('此操作删除该项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await ProjectApi.deleteProject(row.id)
        await this.getProjectsList()

        await this.$notify({
          title: 'Success',
          message: '删除成功！',
          type: 'success',
          duration: 2000
        })
      }).catch(err => {
        console.error(err)
        this.$notify({
          title: 'Fail',
          message: '已取消删除',
          type: 'error',
          duration: 2000
        })
      })
    },
    handleFetchPv(pv) {
      this.dialogPvVisible = true
    }
  }
}
</script>

<style scoped>

.filter-container {
  display: flex;
  justify-content: space-between;
}
.card-section {
  position: relative;
}
.setting-icon {
  cursor: pointer;
  position: absolute;
  top: 0;
  right:0
}
.delete-icon {
  cursor: pointer;
  position: absolute;
  bottom: 0;
  right: 0;
}
</style>
